//
//  ATDrawTrackViewController.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/8.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//  绘制轨迹界面

#import "ATDrawTrackViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "ATDrawTrackManager.h"
#import <SVProgressHUD.h>
#import "ATTrackHistoryViewController.h"
#import "ATStepNumberManager.h"
#import "ATMotionManager.h"

#import "ATQueyTrackViewController.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define iPhone4S [UIScreen mainScreen].bounds.size.height == 480
#define iPhone5S [UIScreen mainScreen].bounds.size.height == 568
#define iPhone6S [UIScreen mainScreen].bounds.size.height == 667
#define iPhonePlus [UIScreen mainScreen].bounds.size.height == 736
#define iPad ([UIScreen mainScreen].bounds.size.height > 736 && [UIScreen mainScreen].bounds.size.height != 812)
#define iPhoneX ([UIScreen mainScreen].bounds.size.height == 812 && [UIScreen mainScreen].bounds.size.width == 375)
#define iPhoneXR [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneXS_MAX [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneX_series (iPhoneX || iPhoneXR || iPhoneXS_MAX)

#define NavHeight (iPhoneX_series ? 88 : 64)
#define TabBarHeight (iPhoneX_series ? 83 : 49)
#define SafeBottomHeight (iPhoneX_series ? 34 : 0)

static NSString * const sid = @"26335"; // 服务id

@interface ATDrawTrackViewController () <MAMapViewDelegate, ATDrawTrackManagerDelegate, ATStepNumberManagerDelegate>

/** 绘制轨迹管理对象 */
@property (nonatomic, strong) ATDrawTrackManager *drawTrackManager;
/** <#name#> */
@property (nonatomic, weak) MAMapView *mapView;

/** 步数 */
@property (nonatomic, weak) UILabel *stepNumLbl;
/** 里程 */
@property (nonatomic, weak) UILabel *distanceLbl;

/** 轨迹点数据数组 */
@property (nonatomic, strong) NSMutableArray<AMapTrackPoint *> *trackPointArray;
/** 开始采集时间 */
@property (nonatomic, strong) NSDate *startDate;
/** 结束采集时间 */
@property (nonatomic, strong) NSDate *endDate;
/** 开始记录 */
@property (nonatomic, assign) BOOL isRecording;
/** 结束记录 */
@property (nonatomic, assign) BOOL isEndRecording;

/** 定时器 */
@property (nonatomic, strong) NSTimer *timer;

/** 计步器管理 */
@property (nonatomic, strong) ATStepNumberManager *stepNumberManager;

/** 加速仪管理 */
@property (nonatomic, strong) ATMotionManager *motionManager;
/** 加速仪的值 */
@property (nonatomic, assign) double accelerameter;

/** <#name#> */
@property (nonatomic, assign) BOOL firstPoint;

@end

@implementation ATDrawTrackViewController

- (ATDrawTrackManager *)drawTrackManager
{
    if (!_drawTrackManager) {
        _drawTrackManager = [ATDrawTrackManager manager];
        _drawTrackManager.gatherInterval = 2;
        _drawTrackManager.packInterval = 10;
    }
    return _drawTrackManager;
}

- (ATStepNumberManager *)stepNumberManager
{
    if (!_stepNumberManager) {
        _stepNumberManager = [ATStepNumberManager manager];
        _stepNumberManager.delegate = self;
    }
    return _stepNumberManager;
}

- (ATMotionManager *)motionManager
{
    if (!_motionManager) {
        _motionManager = [ATMotionManager manager];
    }
    return _motionManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.firstPoint = YES;
    
    [self setupUI];
    
    [self.drawTrackManager setupTrackManager:sid];
    self.drawTrackManager.delegate = self;
    
    self.trackPointArray = [NSMutableArray array];
    
    
    // 开始计步
//    [self.stepNumberManager startCountingStepNumber:[NSDate date]];
    
    // 加速仪管理
    self.motionManager = [ATMotionManager manager];
    
    [self locationIsAvailable];
}

- (void)locationIsAvailable
{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        
    } else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        //定位不能用
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请前往设置开启定位" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

- (void)setupUI
{
    MAMapView *mapView = [[MAMapView alloc] init];
    mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    mapView.frame = self.view.bounds;
    mapView.delegate = self;
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    mapView.showsUserLocation = YES;
    mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    // 不显示罗盘
    mapView.showsCompass = NO;
    
    // 不显示比例尺
    mapView.showsScale = NO;
    
    //是否自定义用户位置精度圈
    mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    MACircle *circle = [MACircle circleWithCenterCoordinate:mapView.userLocation.coordinate radius:0];
    [mapView addOverlay:circle];
    
    //    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    //    self.mapView.distanceFilter = 5; // kCLDistanceFilterNone
    
    mapView.pausesLocationUpdatesAutomatically = NO;
    
    [mapView setZoomLevel:19];
    [self.view addSubview:mapView];
    self.mapView = mapView;
    
    // 修改地图样式
    NSString *path = [NSString stringWithFormat:@"%@/style.data", [NSBundle mainBundle].bundlePath];
    NSData *styleData = [NSData dataWithContentsOfFile:path];
    MAMapCustomStyleOptions *styleOption = [[MAMapCustomStyleOptions alloc] init];
    styleOption.styleData = styleData;
    [self.mapView setCustomMapStyleOptions:styleOption];
    [self.mapView setCustomMapStyleEnabled:YES];
    
    UIButton *stopGatherBtn = [[UIButton alloc] init];
    stopGatherBtn.backgroundColor = [UIColor blackColor];
    stopGatherBtn.frame = CGRectMake(10, SCREEN_HEIGHT - 50, 150, 30);
    [stopGatherBtn addTarget:self action:@selector(stopGatherBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [stopGatherBtn setTitle:@"结束采集" forState:UIControlStateNormal];
    [self.view addSubview:stopGatherBtn];
    
    UIButton *startSerBtn = [[UIButton alloc] init];
    startSerBtn.frame = CGRectMake(10, stopGatherBtn.frame.origin.y - 50, 150, 30);
    startSerBtn.backgroundColor = [UIColor blackColor];
    [startSerBtn addTarget:self action:@selector(startSerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [startSerBtn setTitle:@"开始服务和采集" forState:UIControlStateNormal];
    [self.view addSubview:startSerBtn];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"查询" style:UIBarButtonItemStylePlain target:self action:@selector(queryClick)];
    
    UILabel *stepNumLbl = [[UILabel alloc] init];
    stepNumLbl.frame = CGRectMake(CGRectGetMaxX(startSerBtn.frame) + 10, startSerBtn.frame.origin.y, SCREEN_WIDTH - (CGRectGetMaxX(startSerBtn.frame) + 10) - 10, 30);
    stepNumLbl.textAlignment = NSTextAlignmentRight;
    stepNumLbl.textColor = [UIColor whiteColor];
    stepNumLbl.backgroundColor = [UIColor blackColor];
    [self.view addSubview:stepNumLbl];
    self.stepNumLbl = stepNumLbl;
    
    UILabel *distanceLbl = [[UILabel alloc] init];
    distanceLbl.frame = CGRectMake(CGRectGetMaxX(startSerBtn.frame) + 10, stopGatherBtn.frame.origin.y, SCREEN_WIDTH - (CGRectGetMaxX(startSerBtn.frame) + 10) - 10, 30);
    distanceLbl.textAlignment = NSTextAlignmentRight;
    distanceLbl.textColor = [UIColor whiteColor];
    distanceLbl.backgroundColor = [UIColor blackColor];
    [self.view addSubview:distanceLbl];
    self.distanceLbl = distanceLbl;
}

- (void)queryClick
{
    ATTrackHistoryViewController *queryVc = [[ATTrackHistoryViewController alloc] init];
    queryVc.trackID = self.drawTrackManager.trackID;
    queryVc.terminalID = self.drawTrackManager.terminalID;
    queryVc.startDate = self.startDate;
    queryVc.endDate = self.endDate;
    [self.navigationController pushViewController:queryVc animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    // 返回删除定时器
    if (self.navigationController.topViewController == nil) {
        [self removeTimer];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)addtimer
{
    if (self.timer) {
        [self removeTimer];
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)removeTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)timerAction
{
    
//    __weak typeof(self) _weakSelf = self;
//    [self.motionManager start:^(double accelerameter) {
//        NSLog(@"accelerameter: %f", accelerameter);
//        _weakSelf.accelerameter = accelerameter;
//
//        if (_weakSelf.accelerameter) {
//            //立即停止更新加速仪（很重要！），不然会执行多次
//            [_weakSelf.motionManager stop];
//        }
//    }];
    
    [self.drawTrackManager queryLastestPoint];
    
    NSDate *endDate = [NSDate date];
    if (self.endDate) {
        endDate = self.endDate;
    }
    [self.stepNumberManager stepNumberWithStartDate:self.startDate endDate:endDate];
//    [self queryTracks];
}

- (void)queryTracks
{
    NSLog(@"serviceID:%@, terminalID:%@, trackID:%@, startDate:%@, endDate:%@", self.drawTrackManager.serviceID, self.drawTrackManager.terminalID, self.drawTrackManager.trackID, self.startDate, [NSDate date]);
    AMapTrackQueryTrackInfoRequest *request = [[AMapTrackQueryTrackInfoRequest alloc] init];
    request.serviceID = self.drawTrackManager.serviceID;
    request.terminalID = self.drawTrackManager.terminalID;
    request.trackID = self.drawTrackManager.trackID;
    request.startTime = [self.startDate timeIntervalSince1970] * 1000;
    request.endTime = [[NSDate date] timeIntervalSince1970] * 1000;
    
    [self.drawTrackManager queryTrackInfo:request];
}

- (void)stopGatherBtnClick
{
    [self.drawTrackManager stopGather];
}

- (void)startSerBtnClick
{
    NSLog(@"点击开始服务");
    [self.drawTrackManager startServiceWithTerminalName:@"测试终端1"];
}

#pragma mark - ATDrawTrackManagerDelegate
- (void)startServiceIsSuccess:(BOOL)isSuccess
{
    if (isSuccess) {
        [SVProgressHUD showSuccessWithStatus:@"开启服务成功"];
    }
}

- (void)startGatherAndPackIsSuccess:(BOOL)isSuccess
{
    if (isSuccess) {
        [SVProgressHUD showSuccessWithStatus:@"开始采集成功"];
        
        self.startDate = [NSDate date];
        self.isRecording = YES;
        self.isEndRecording = NO;
        
        // 添加定时器
        [self addtimer];
    }
}

- (void)stopGatherAndPackIsSuccess:(BOOL)isSuccess
{
    if (isSuccess) {
        [SVProgressHUD showSuccessWithStatus:@"结束采集成功"];
        self.endDate = [NSDate date];
        self.isRecording = NO;
        self.isEndRecording = YES;
        
        // 删除定时器
        [self removeTimer];
        
        [self.drawTrackManager stopService];
        // 停止计步
//        [self.stepNumberManager stopCountingStepNumber];
    }
}

- (void)stopServiceIsSuccess:(BOOL)isSuccess
{
    if (isSuccess) {
        [SVProgressHUD showSuccessWithStatus:@"结束服务成功"];
    }
}

- (void)queryLastPointDone:(AMapTrackQueryLastPointRequest *)request response:(AMapTrackQueryLastPointResponse *)response
{
    //查询成功
    NSLog(@"onQueryLastPointDone====%f=====%f===%f", response.lastPoint.coordinate.latitude, response.lastPoint.coordinate.longitude, response.lastPoint.accuracy);

//    if (self.trackPointArray.count < 1) {
//
//        [self.trackPointArray addObject:response.lastPoint];
//    } else {
//
//        [self.trackPointArray addObject:response.lastPoint];
//
//        CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:self.trackPointArray.lastObject.coordinate.latitude longitude:self.trackPointArray.lastObject.coordinate.longitude];
//
//        CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:response.lastPoint.coordinate.latitude longitude:response.lastPoint.coordinate.longitude];

//        double distance = [currentLocation distanceFromLocation:endLocation];
//
//        NSLog(@"distance == %f", distance);
//        if (distance < 100) { // 当前位置跟上一个位置小于100时才绘制
//            [self.trackPointArray addObject:response.lastPoint];
//
//            [self.mapView removeOverlays:[self.mapView overlays]];
//            [self showPolylineWithTrackPoints:self.trackPointArray];
//            [self.mapView showOverlays:self.mapView.overlays animated:NO];
//        }
//    }

//    if (self.accelerameter > 1.5) { // 加速仪的值大于1.5才绘制轨迹
    
    if (self.trackPointArray.count == 0 && self.firstPoint) {
        self.firstPoint = NO;
        return;
    }
    
    if (self.trackPointArray.count > 1) {
        CLLocation *lastLocation = [[CLLocation alloc] initWithLatitude:self.trackPointArray.lastObject.coordinate.latitude longitude:self.trackPointArray.lastObject.coordinate.longitude];
        CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:response.lastPoint.coordinate.latitude longitude:response.lastPoint.coordinate.longitude];
        double distance = [lastLocation distanceFromLocation:currentLocation];
        NSLog(@"distance = %f", distance);
    }
    
    [self.trackPointArray addObject:response.lastPoint];
    
    [self.mapView removeOverlays:[self.mapView overlays]];
    [self showPolylineWithTrackPoints:self.trackPointArray];
//        [self.mapView showOverlays:self.mapView.overlays animated:NO]; // 调用后会完整显示轨迹
//    }
}

- (void)queryTrackHistoryAndDistanceDone:(AMapTrackQueryTrackHistoryAndDistanceRequest *)request response:(AMapTrackQueryTrackHistoryAndDistanceResponse *)response
{
    if ([[response points] count] > 0) {
        //        [self.mapView removeOverlays:[self.mapView overlays]];
        
        [self showPolylineWithTrackPoints:[response points]];
        [self.mapView showOverlays:self.mapView.overlays animated:NO];
        
        if (response.points.count == self.drawTrackManager.pageSize) {
            self.drawTrackManager.pageIndex++;
            
            [self queryTracks];
        }
    }
}

- (void)queryTrackInfoDone:(AMapTrackQueryTrackInfoRequest *)request response:(AMapTrackQueryTrackInfoResponse *)response
{
    NSLog(@"onQueryTrackInfoDone%@", response.formattedDescription);
    [self.mapView removeOverlays:[self.mapView overlays]];
    for (AMapTrackBasicTrack *track in response.tracks) {
        if ([[track points] count] > 0) {
            [self showPolylineWithTrackPoints:[track points]];
        }
    }
//    [self.mapView showOverlays:self.mapView.overlays animated:NO];
}

#pragma mark - Helper
- (void)showPolylineWithTrackPoints:(NSArray<AMapTrackPoint *> *)points {
    int pointCount = (int)[points count];
    
    CLLocationCoordinate2D *allCoordinates = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < pointCount; i++) {
        allCoordinates[i].latitude = [[points objectAtIndex:i] coordinate].latitude;
        allCoordinates[i].longitude = [[points objectAtIndex:i] coordinate].longitude;
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:allCoordinates count:pointCount];
    [self.mapView addOverlay:polyline];
    
    if (allCoordinates) {
        free(allCoordinates);
        allCoordinates = NULL;
    }
}

#pragma mark - MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation) {
        return;
    }
    
//    NSLog(@"didUpdateUserLocation====%f=====%f=", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    
    if (!self.isRecording) {
        return;
    }
    
    // 查询最后一个轨迹点
//    [self.drawTrackManager queryLastestPoint];
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth = 5.f;
        polylineRenderer.strokeColor = [UIColor greenColor];
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType = kMALineCapRound;
        
        return polylineRenderer;
    }
    
    if ([overlay isKindOfClass:[MACircle class]]) {
        
    }
    
    return nil;
}

#pragma mark - ATStepNumberManagerDelegate
- (void)stepNumber:(NSDictionary *)dict
{
//    NSLog(@"计步器数据 dict = %@", dict);
    
    self.stepNumLbl.text = [NSString stringWithFormat:@"%@步", dict[@"numberOfSteps"]];
    self.distanceLbl.text = [NSString stringWithFormat:@"%@米", dict[@"distance"]];
}

- (void)dealloc
{
    NSLog(@"ATDrawTrackVc------dealloc");
    
    [self.drawTrackManager deallocDoSomething];
    
    [self.mapView removeFromSuperview];
    self.mapView.delegate = nil;
    self.mapView = nil;
}

@end
